package com.sls.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sls.mall.common.constant.ProductConstant;
import com.sls.mall.product.dao.AttrAttrgroupRelationDao;
import com.sls.mall.product.dao.AttrGroupDao;
import com.sls.mall.product.dao.CategoryDao;
import com.sls.mall.product.entity.AttrAttrgroupRelationEntity;
import com.sls.mall.product.entity.AttrGroupEntity;
import com.sls.mall.product.entity.CategoryEntity;
import com.sls.mall.product.service.CategoryService;
import com.sls.mall.product.vo.AttrGroupRelationVO;
import com.sls.mall.product.vo.AttrRespVO;
import com.sls.mall.product.vo.AttrVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Beans;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sls.mall.common.utils.PageUtils;
import com.sls.mall.common.utils.Query;

import com.sls.mall.product.dao.AttrDao;
import com.sls.mall.product.entity.AttrEntity;
import com.sls.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;




    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }


    @Transactional
    public void saveAttr(AttrVO attrVO)
    {
        AttrEntity attrEntity = new AttrEntity();

        BeanUtils.copyProperties(attrVO,attrEntity);

        // 保存基本信息
        save(attrEntity);

        // 保存关联信息
        if (attrVO.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();

            attrAttrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrAttrgroupRelationEntity.getAttrId());

            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }


    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId,String type) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();

        if (catelogId != 0)
        {
            queryWrapper.eq("catelog_id",catelogId).eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        }

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and((wapper) -> {
                wapper.eq("attr_id", key).or().like("arrt_name", key);
            });
        }
        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVO> respVOList = records.stream().map((attrEntity) -> {

            AttrRespVO attrRespVO = new AttrRespVO();

            BeanUtils.copyProperties(attrEntity, attrRespVO);

            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

            if ("base".equalsIgnoreCase(type))
            {
                if (attrAttrgroupRelationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());

                    if (attrGroupEntity != null && attrGroupEntity.getAttrGroupName() != null) {
                        attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());

            if (categoryEntity != null) {
                attrRespVO.setCatelogName(categoryEntity.getName());
            }

            return attrRespVO;

        }).collect(Collectors.toList());


        pageUtils.setList(respVOList);

        return pageUtils;

    }


    public AttrRespVO getAttrInfo(Long arrtId)
    {
        AttrRespVO attrRespVO = new AttrRespVO();

        AttrEntity attrEntity = getById(arrtId);

        BeanUtils.copyProperties(attrEntity,attrRespVO);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", arrtId));

            // 1. 设置分组信息
            if (attrAttrgroupRelationEntity != null) {
                attrRespVO.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());

                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());

                if (attrGroupEntity != null) {
                    attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //2. 设置分类信息
        Long catelogId = attrEntity.getCatelogId();

        Long[] catelogPath = categoryService.findCatelogPath(catelogId);

        attrRespVO.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);

        if(categoryEntity != null)
        {
            attrRespVO.setCatelogName(categoryEntity.getName());
        }

        return attrRespVO;

    }

    @Transactional
    @Override
    public void updateAttr(AttrVO attr) {

        AttrEntity attrEntity = new AttrEntity();

        BeanUtils.copyProperties(attr,attrEntity);

        updateById(attrEntity);

        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //1. 修改分组关联
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();

            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());

            // 查看记录是否有 有的话 就修改，没有就新增
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));

            if (count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));

            } else {

                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> collect = entities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if (collect == null || collect.size() == 0)
        {
            return null;
        }

        List<AttrEntity> attrEntities = listByIds(collect);

        return attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVO[] attrGroupRelationVO) {

        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(attrGroupRelationVO).stream().map(item -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);

            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(collect);

    }

    /**
     *  获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        // 1. 当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);

        Long catelogId = attrGroupEntity.getCatelogId();

        // 2.  当前分组只能关联别的分组没有引用的属性
        // 2.1 当前分类下的其他分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        List<Long> groupids = attrGroupEntities.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2 这些分组的关联的属性
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",Arrays.asList(groupids)));

        List<Long> attrids = entities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3 从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrids != null && attrids.size() > 0)
        {
            queryWrapper.notIn("attr_id", attrids);
        }

        String key = (String) params.get("key");

        if (StringUtils.isNotEmpty(key))
        {
            queryWrapper.and(wapper -> {
                wapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }
}